package app

import (
	"gitee.com/theegg/go-brick/app/service/api_error"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Response struct {
	Ctx  *gin.Context
	Lang string
}

func NewResponse(ctx *gin.Context) *Response {
	return &Response{
		Ctx: ctx,
	}
}

// ＠title JsonReturn
// @des 返回http 200 的json数据
func (r *Response) JsonReturn(success bool, msg string, data interface{}) {
	body := gin.H{
		"msg":     msg,
		"success": success,
		"data":    data,
	}

	r.Ctx.JSON(http.StatusOK, body)
}

// ＠title JsonReturn
// @des 返回http 200 的json数据
func (r *Response) JsonI18nReturn(errCode int, errCodeParams []interface{}, data interface{}) {
	errCodeHandle, err := GetErrorCodeHandle(r.Ctx)
	if err != nil {
		panic(err.Error())
	}

	errCodeHandle.WithCode(errCode)
	errCodeHandle.WithParams(errCodeParams)

	body := gin.H{
		"msg":     errCodeHandle.GetMeg(),
		"success": errCodeHandle.Code%100 == 0,
		"data":    data,
	}

	r.Ctx.JSON(http.StatusOK, body)
}

// ＠title ErrorReturn
// @des 返回 错误头 的json数据
func (r *Response) ErrorReturn(err *ResError) {
	rp := gin.H{"code": err.Code(), "msg": err.Msg()}
	data := err.Data()

	if len(data) > 0 {
		rp["data"] = data
	}

	r.Ctx.JSON(err.StatusCode(), rp)
}

// @title GetErrorCodeHandle
// @description 获取错误吗处理逻辑
func GetErrorCodeHandle(c *gin.Context) (*api_error.ApiError, error) {
	// 区域
	platform, ok := c.Get("c_platform_region")
	if !ok {
		platform = "user"
	}

	// 默认中文
	lang, ok := c.Get("c_api_error_lang")
	if !ok {
		lang = "cn"
	}

	return api_error.New(platform.(string), lang.(string)), nil
}
